import { observable, action } from 'mobx';
import * as batchAddAPI from '../../apis/batchAdd';
import API from '../../apis';
import EditTableStore from '../mobxTable/table';
import { getColumns } from '../data/batchAdd';
import { message,Modal} from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import { showExpendError } from '../../util/cubeUtil';
import $ from "jquery";
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;

export interface BatchAddStoreProps {

}

export default class BatchAddStore implements BatchAddStoreProps {

    @observable iconInfo = {
        icon: "icon-coms-ModelingEngine",
        iconColor: "#fff",
        iconBg: "#96358a"
    }
    @observable loading=false;
    @observable title='';
    @observable customid='';
    @observable editTableStore: EditTableStore = new EditTableStore();
    @observable hasRight=true;
    @observable visible = false;
    @observable isfrontmultlang: boolean;
    @observable bathAddExpendname = '';
    @observable isButtonClick = true;
    @observable params = {} as any;
    


    @action
    init=()=>{
        this.getIconInfo(this.customid);
        this.loading=true;
        batchAddAPI.getColumnInfo({ ...this.params,customid: this.customid}).then(action(({ error, status, dataList, optionsMap, browserMap, title,hasRight,uploadMap,bathAddExpendname }) => {
          
          if (status == '1') {
          
            this.bathAddExpendname = bathAddExpendname;
            if ( dataList.length == 0) {
              message.warn(getLabel(510166,'新增列表字段定义中批量新增没有勾选，请联系管理员处理！'));
              this.loading=false;
            }

            this.hasRight=hasRight;
            if(hasRight){
              this.title=title;
              this.editTableStore.initTableForm([], getColumns(dataList, optionsMap, browserMap, this.editTableStore,uploadMap,this.buildsqlkey(dataList)));
              this.addNewData();
              // 判断
            }
          } else {
            message.error(error);
            throw error;
          }
          this.loading = false;
        }));
    }

   

    @action
    save = (callback?: Function) => {
      if(this.isButtonClick == false){
        return;
      }
      if(this.loading){
        return;
      }
      let datas = this.editTableStore.form.$(`tableForm`).values();
      //重复验证
      this.loading=true;
      API.batchEditGetVerifyField({ customid: this.customid }).then(action(({ error, status, result }) => {
        if (status == '1') {
          if (result && result.VerifyField && result.VerifyField.length > 0) {
            let fields = '';
            result.VerifyField.forEach(element => {
              fields += element.fieldids + ',';
            });
            if (fields == '') {
              this.doSave(datas,callback);
            }
            var fieldArray = fields.split(',');
            var verifyDataObj = new Array();
            let columns = this.editTableStore.columns;
            _.reverse(datas).forEach((item, index) => {
              var fieldvalues = {};
              fieldArray.forEach((fieldid, index) => {
                columns.forEach(element => {
                  if (element.fieldid == fieldid) {
                    fieldvalues['pluginName' + fieldid] = item[element.key];
                  }
                });
              });
              fieldvalues[result.primaryKeyPluginName] = item['randomFieldId'];
              if (result.detailPrimaryKeyPluginName) {
                fieldvalues[result.detailPrimaryKeyPluginName] = item['randomFieldSubKeyd_id'];
              }
              fieldvalues['^_^rownum^_^'] = index;
              verifyDataObj.push(fieldvalues);
            });
            var jsonstr = JSON.stringify(verifyDataObj);
            API.batchEditVerifyData({
              customid: this.customid,
              data: jsonstr,
              isBathAdd:'1'
            }).then(action(({ error, status, result, colorMap }) => {
              if (status == '1') {
                this.checkFail(result, this.doSave, datas, columns, colorMap,callback);
              } else {
                message.error(error)
                if(callback){callback()}
                throw error;
              }
            }));
          } else {
            this.doSave(datas,callback);
          }
        } else {
          message.error(error)
          if(callback){callback()}
          throw error;
        }
        //this.loading=false;
        
    //  if(callback){callback()} 
      }));
    }

    //重复验证返回信息处理
    checkFail = (result, func, data, columns, colorMap,callback?: Function) => {
      if (result.verify || result.confirmbefore && result.confirmbefore.verify) {
        if(callback){callback()};
        $($('.cube-table-fixed')[1]).find('td').css('backgroundColor', '');
        var detail = result.detail;
        detail && detail.forEach((elem, index) => {
          let columnsIndex = elem.fields.map(element => {
            return _.findIndex(columns, function (o: any) {
              let fieldname = element.detailtable ? 'd_' + element.fieldname : element.fieldname;
              return o['key'] == fieldname;
            })
          });
          let tableNode: any = document.getElementsByClassName('cube-table-fixed')[1];
          if(elem.rownums!=null&&elem.rownums!=undefined&&elem.rownums.constructor==Number)elem.rownums=[elem.rownums];
          elem.rownums && (elem.rownums.constructor == Array) && elem.rownums.forEach(rowNum => {
            columnsIndex.forEach(columnNum => {
              if(columnNum>=0){
                columnNum+=1;
                if (tableNode.rows[rowNum] && tableNode.rows[rowNum].cells[columnNum]) {
                  tableNode.rows[rowNum].cells[columnNum].style.backgroundColor = colorMap[elem.verifyid];
                }
              }
            });
          });
        });
        var operate = result.operate || result.confirmbefore && result.confirmbefore.operate;
        if (!operate) {
          operate = '0';
        }
        if (operate == '0') {
          const that=this;
          Modal.info({
            title: getLabel(558, '提示'),
            content: <div dangerouslySetInnerHTML={{ __html: result.msg }} />,
            onOk() {
              that.loading=false;
              that.isButtonClick=true;
            },
          });
        } else {
          if (result.confirmbefore) {
            const that=this;
            this.checkFail(result.confirmbefore, () => {
              Modal.confirm({
                title: <div dangerouslySetInnerHTML={{ __html: result.msg || '是否继续？' }} />,
                okText: getLabel(382958, '继续'),
                cancelText: getLabel(201, '取消'),
                onOk: () => {
                  func && func(data,callback);
                },
                onCancel() {
                  that.loading=false;
                  that.isButtonClick=true;
                }
              });
            }, data, columns, colorMap);
          } else {
            const that=this;
            Modal.confirm({
              title: <div dangerouslySetInnerHTML={{ __html: result.msg }} />,
              okText: getLabel(382958, '继续'),
              cancelText: getLabel(201, '取消'),
              onOk: () => {
                func && func(data,callback);
              },
              onCancel() {
                that.loading=false;
                that.isButtonClick=true;
              }
            });
          }
        }
      } else {
        this.doSave(data,callback);
      }
    }

    @action
    doSave = (data,callback?: Function) => {
      this.loading=true;
      batchAddAPI.saveDatas({...this.params,customid:this.customid,datas:JSON.stringify(this.editTableStore.form.$(`tableForm`).values())}).then(({error, status,errorCode,pageExpendResult})=>{
        if (status == '1') {
          if(errorCode=='-1'){
            message.error(error);
          }else{
            try{
              let searchTemp = window['cubeStore']['Search']
              let isTreeList = searchTemp && searchTemp.dataShowtype === 'treeType' && searchTemp.changeSearch == '1';// 分组包含 组合转换，单独判断
              if(isTreeList){
                searchTemp.refresh()
              }else{
                window['_table'].reLoad();
              }
            }catch(e){
              window['cubeStore']['Search'].refresh()
            }
            // window['_table'].reLoad();
            if(pageExpendResult&&pageExpendResult.haveError){
              showExpendError(pageExpendResult,this.getHref());
              return;
            }
            message.success(getLabel(30700, '操作成功'));
            this.visible=false;
            if(callback){callback()}
            this.editTableStore.initTableForm([]);
            this.editTableStore.selectedRowKeys=[];
            this.addNewData();
          }
        } else {
          message.error(error);
          throw error;
        }
        this.loading=false;
        this.isButtonClick = true;
      });
    }

    getHref =()=>{
      let href="/spa/cube/index.html#/main/cube/search?customid="+this.customid+"&";
      return href;
    }

    buildsqlkey=(dataList)=>{
      let sqlNeedKey:any={randomkey:new Date().getTime()};
      dataList.map(item=>{
        _.set(sqlNeedKey,item.fieldname,item.sqlNeedFieldKey)
      });
      return sqlNeedKey;
    }
    
    @action
    addNewData=(data={})=>{
      let newData:any={randomkey:new Date().getTime()};
      this.editTableStore.columns.forEach(item=>{
        newData[item.key]=item['fieldhtmltype']!="6" && data[item.key]?data[item.key]:'';
        newData[item.key+'span']=item['fieldhtmltype']!="6" && data[item.key+'span']?data[item.key+'span']:'';
      });
      this.editTableStore.addDatas([newData]);
    }

    @action
    deleteData=()=>{
      this.editTableStore.delDatas(this.editTableStore.selectedRowKeys);
      this.editTableStore.selectedRowKeys=[];
    }

    @action
    copyData=()=>{
      this.editTableStore.selectedRowKeys.forEach(key=>{
        this.addNewData(this.editTableStore.form.$(`tableForm.${key}`).values());
      });
    }

    @action
    getIconInfo = (customid) => {
      API.getAppInfoByID({ customid }).then((data: any) => {
        if (data.status == "1") {
          this.iconInfo = {
            icon: data.icon || "icon-coms-ModelingEngine",
            iconColor: data.iconColor || "#fff",
            iconBg: data.iconBg || "#96358a"
          };
        }
      })
    }

    @action
    update = (param: any) => {
        for (let key in param) {
            if (param.hasOwnProperty(key)) {
                this[key] = param[key]
            }
        }
    }

}
